<template>
	<view class="main">
		<view class="">
			<u-input v-model="pwdInput" border :maxlength="1000" @focus="pwdInputFocus" />
			<view class="" style="padding:20rpx">
				<u-radio-group @change="radioGroupChange">
					<u-radio name="encrypt">加密</u-radio>
					<u-radio name="decrypt">解密</u-radio>
				</u-radio-group>
			</view>
			<u-input v-model="pwdOutput" border :maxlength="1000" />
		</view>

		<button type="default" @click="handleTest">测试</button>
		<view class="cookie-x"><u-input v-model="sourceInput" border :maxlength="1000" :height="400" type="textarea" auto-height @input="cookieChange" /></view>
		<view class="params">
			<u-form :model="form" :rules="formRules" ref="uForm" label-width="auto">
				<u-form-item required label="SESSION" prop="SESSION"><u-input v-model="form.SESSION" :maxlength="1000" /></u-form-item>
				<u-form-item required label="JSESSIONTOKEN" prop="JSESSIONTOKEN"><u-input v-model="form.JSESSIONTOKEN" :maxlength="1000" /></u-form-item>
				<u-form-item required label="SIAMTGT" prop="SIAMTGT"><u-input v-model="form.SIAMTGT" :maxlength="1000" /></u-form-item>
				<u-form-item required label="USERTOKEN" prop="USERTOKEN"><u-input v-model="form.USERTOKEN" placeholder="请输入账号" /></u-form-item>
			</u-form>
		</view>
		<view class="operater-x"><u-button :loading="submitLoading" :ripple="true" ripple-bg-color="#909399" type="primary" shape="square" @click="test">主要按钮</u-button></view>
		<view class="record-x">
			<u-time-line>
				<u-time-line-item nodeTop="2" v-for="(item, index) in recordList" :key="index">
					<!-- 此处自定义了左边内容，用一个图标替代 -->
					<template v-slot:node>
						<view class="u-node" style="background: #19be6b;">
							<!-- 此处为uView的icon组件 -->
							<u-icon name="pushpin-fill" color="#fff" :size="24"></u-icon>
						</view>
					</template>
					<template v-slot:content>
						<view>{{ item }}</view>
					</template>
				</u-time-line-item>
			</u-time-line>
		</view>
		<!-- 提示 -->
		<u-toast ref="uToast" />
		<!-- 底部导航栏 -->
		<u-tabbar :list="tabbar"></u-tabbar>
	</view>
</template>
<script>
import { mapMutations, mapGetters } from 'vuex';
export default {
	data() {
		return {
			pwdInput: '',
			pwdOutput: '',
			tabbar: '',
			submitLoading: false,
			sourceInput: '',
			cookiestr:
				'SESSION=153f1f8c-fe01-4f9f-ba77-fc70e66c0682;JSESSIONTOKEN=218604276aedc8b6726f2b151539d8e5071491ba3aeaae789f8e82870d30195a8837c443301041f71b4553408d544241f9f29ddb3358b23ab3c9c7460a8620bc664b191ce2a5a425c939fac43dab56f2e41297d6f326d29a2df9c645c27e730a;SIAMTGT=TGT-1821643-FRz7MLZiaPlMYWU3dMdiqDSfXJeCjkPaWz2j5I1jejgTtgaK0t-SIAM;USERTOKEN=wenyi2.lin',
			recordList: [],
			form: {
				SESSION: '',
				JSESSIONTOKEN: '',
				SIAMTGT: '',
				USERTOKEN: ''
			},
			rules: {
				SESSION: [
					{
						required: true,
						message: '请输入SESSION',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur']
					}
				],
				JSESSIONTOKEN: [
					{
						required: true,
						message: '请输入JSESSIONTOKEN',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur']
					}
				],
				SIAMTGT: [
					{
						required: true,
						message: '请输入SIAMTGT',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur']
					}
				],
				USERTOKEN: [
					{
						required: true,
						message: '请输入USERTOKEN',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur']
					}
				]
			}
		};
	},
	onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
	onShow() {
		this.tabbar = getApp().globalData.tabbar;
	},
	computed: {
		...mapGetters('user', ['cookieTclGet'])
	},
	methods: {
		showToast(title = '', type = 'error') {
			if (Number.isInteger(type)) {
				switch (type) {
					case 0:
						type = 'success';
						break;
					case 1:
						type = 'error';
						break;
					default:
						break;
				}
			}
			this.$refs.uToast.show({
				title,
				type
			});
		},
		pwdInputFocus(v){
			uni.getClipboardData({
			    success: ({data=""} ={}) => {
					if(data){
						this.pwdInput = data.trim()
					}
			    }
			});
		},
		radioGroupChange(v) {
			const pwdInput = this.pwdInput;
			if (!pwdInput) {
				this.showToast('输入加密/解密参数不能为空');
				return;
			}
			if (v == 'encrypt') {
				this.pwdOutput = this.$utils.encrypt(pwdInput);
			}

			if (v == 'decrypt') {
				 const  pwdOutput = this.$utils.decrypt(pwdInput);
				 this.pwdOutput  = pwdOutput 
				//复制
				
				if(pwdOutput){
					uni.setClipboardData({
					    data: pwdOutput,
					    success: function () {
					        console.log('success');
					    }
					});
				}
				
			}
		},
		handleTest() {
			 uni.setStorageSync('storage_key', 'hello');
			 const value = uni.getStorageSync('COOKIE_TCL');
			 console.log(value);
			// const encryptPwd = this.$utils.encrypt('tea##666');
			// const decryptPwd = this.$utils.decrypt(encryptPwd);
		},
		cookieChange(v) {
			if (v) {
				const parsData = JSON.parse(this.sourceInput);
				const formData = this.form;
				if (parsData instanceof Object) {
					formData['SESSION'] = parsData['jsessionid'];
					formData['JSESSIONTOKEN'] = parsData['jsessiontoken'];
					formData['SIAMTGT'] = parsData['data'];
				}
			}
		},
		sleep(n = 1000) {
			let startTime = new Date().getTime();
			while (true) {
				let curTime = new Date().getTime();
				if (curTime - startTime > n) {
					break;
				}
			}
		},
		async generateAnswerTest(regId, modId, cookie) {
			const {
				1: {
					data: { data }
				}
			} = await uni.request({
				url: 'https://tlearning-sdbg.tcl.com/api/activityRegister/generateAnswerTest.shtml',
				method: 'GET',
				data: {
					ts: new Date().getTime(),
					activity_register_id: regId,
					activity_module_id: modId
				},
				header: {
					Cookie: cookie
				}
			});
			let result = null;
			if (data instanceof Object) {
				const {
					test: { testCategories }
				} = data;
				const testCategoryAnswers = testCategories.map(mi => {
					const testQuestionAnswers = mi.testQuestions.map(qmi => {
						const question_id = qmi.question_id;
						return {
							question_id,
							answer_content: ''
						};
					});
					return {
						test_category_id: mi.id,
						testQuestionAnswers
					};
				});
				result = {
					activity_register_id: regId,
					activity_module_id: modId,
					testCategoryAnswers
				};
			}
			// 初始提交
			let initStatus = '';
			if (result) {
				initStatus = await this.submitTestAnswer(result, cookie);
			}
			return [result, initStatus];
		},
		async submitTestAnswer(submitObj = {}, cookie) {
			const {
				1: {
					data: { data }
				}
			} = await uni.request({
				url: 'https://tlearning-sdbg.tcl.com/api/activityRegister/submitTestAnswer.shtml',
				method: 'POST',
				data: {
					ts: new Date().getTime(),
					...submitObj
				},
				header: {
					Cookie: cookie
				}
			});

			return data;
		},
		// 获取正确答案并且提交
		async submitTestAnswerTrue(regId, modId, cookie) {
			//查答案
			const res = await this.queryTestAnswerDetails(regId, modId, cookie);
			const { learn_status } = await this.submitTestAnswer(res, cookie);
			return learn_status;
		},

		// 查询答案
		async queryTestAnswerDetails(regId, modId, cookie) {
			const {
				1: {
					data: { data }
				}
			} = await uni.request({
				url: 'https://tlearning-sdbg.tcl.com/api/activityRegister/queryTestAnswerDetails.shtml',
				method: 'GET',
				data: {
					ts: new Date().getTime(),
					activity_register_id: regId,
					activity_module_id: modId,
					index: 0
				},
				header: {
					Cookie: cookie
				}
			});
			let result = null;
			if (data instanceof Object) {
				const {
					test: { testCategories }
				} = data;
				const testCategoryAnswers = testCategories.map(mi => {
					const testQuestionAnswers = mi.testQuestions.map(qmi => {
						let answerContentStr = '';
						const question_id = qmi.question_id;
						const answerContent = qmi.answer_content;
						const dicQueName = qmi.dic_que_name;
						const queAnswer = qmi.que_answer;
						if (queAnswer) {
							const questionOptions = qmi.questionOptions;
							if (Array.isArray(questionOptions) && questionOptions.length) {
								const questionOptionsFilter = questionOptions.filter(fi => queAnswer.includes(fi.option_order));
								if (questionOptionsFilter.length) {
									const questionOptionsMap = questionOptionsFilter.map(qmi => qmi.id);
									answerContentStr = questionOptionsMap.join('~');
								}
							}
						}

						// 判断题
						if (dicQueName == '判断题') {
							const que_answer = qmi.que_answer;
							if (que_answer == '正确') {
								answerContentStr = 'T';
							} else {
								answerContentStr = 'F';
							}
						}

						// 填空题
						if (dicQueName == '填空题') {
							const questionOptions = qmi.questionOptions;
							if (Array.isArray(questionOptions) && questionOptions.length) {
								answerContentStr = questionOptions[0].option_text;
							}
						}

						return {
							question_id,
							answer_content: answerContentStr
						};
					});
					return {
						test_category_id: mi.id,
						testQuestionAnswers
					};
				});
				result = {
					activity_register_id: regId,
					activity_module_id: modId,
					testCategoryAnswers
				};
			}
			return result;
		},
		async fetchMHId(pid, actId, cookie) {
			const res = await uni.request({
				url: 'https://tlearning-sdbg.tcl.com/api/activityRegister/queryLearnerActivityModule.shtml',
				method: 'GET',
				data: {
					ts: new Date().getTime(),
					parent_class_id: pid,
					activity_id: actId
				},
				header: {
					Cookie: cookie
				}
			});
			const {
				data: { data: modules }
			} = res[1];

			if (typeof modules == 'string') {
				return {
					status: false,
					data: modules
				};
			}

			const {
				activity_register_id: videoRegId = '',
				id: videoModId = '',
				mod_name: videoModName = '',
				mod_times: videoModTimes = '',
				registerModule: { learn_status: videoLearnStatus = '' } = {}
			} = modules[0] || {};
			const testModel = modules.length == 1 ? modules[0] : modules[1];
			const {
				activity_register_id: testRegId = '',
				id: testModId = '',
				mod_name: testNModName,
				mod_times: testModTimes = '',
				registerModule: { learn_status: testLearnStatus = '' } = {}
			} = testModel;
			const result = [[videoRegId, videoModId, videoModName, videoModTimes, videoLearnStatus], [testRegId, testModId, testNModName, testModTimes, testLearnStatus]];
			return { status: true, data: result };
		},
		async activateModule(arid, amid, cookie) {
			const res = await uni.request({
				url: 'https://tlearning-sdbg.tcl.com/api/activityRegister/learnActivityModule.shtml',
				method: 'GET',
				data: {
					ts: new Date().getTime(),
					activity_register_id: arid,
					activity_module_id: amid
				},
				header: {
					Cookie: cookie
				}
			});
			const {
				data: {
					data: { register_module_history_id, activity_name }
				}
			} = res[1];
			return register_module_history_id;
		},
		async finishVidoLearn(regId, modId, cookie, videoModTimes = 10000) {
			const rmhId = await this.activateModule(regId, modId, cookie);
			const res = await uni.request({
				url: 'https://tlearning-sdbg.tcl.com/api/activityRegister/learnVideoAudioDocumentImgText.shtml',
				method: 'GET',
				data: {
					ts: new Date().getTime(),
					register_module_history_id: rmhId,
					visit_position: 0,
					visit_seconds: videoModTimes
				},
				header: {
					Cookie: cookie
				}
			});
			const { data: { data: { learn_status = '' } = {} } = {} } = res[1] || {};
			return learn_status;
		},
		async test() {
			let cookieTclGet = this.cookieTclGet;
			let storageCookieTcl =  uni.getStorageSync('COOKIE_TCL')
			if (cookieTclGet.trim() == '' && storageCookieTcl == '') {
				const vailRes = await this.$refs.uForm.validate();
				if (!vailRes) {
					uni.showToast({
						icon: 'error',
						title: '验证失败'
					});
					return;
				}
			}
			if (this.submitLoading) {
				return;
			}
			this.submitLoading = true;
			setTimeout(() => {
				this.submitLoading = false;
			}, 10000);
			try {
				const formData = this.form;
				let tempCookieStr = '';
				for (let [key, value] of Object.entries(formData)) {
					tempCookieStr += `${key}=${value};`;
				}
				
				let cookiestr = cookieTclGet || storageCookieTcl  || tempCookieStr;
				const curTime = new Date().getTime();
				const recordList = this.recordList;
				const res = await uni.request({
					url: 'https://tlearning-sdbg.tcl.com/api/bdm/activity/getBasicEntityPage/activity_.shtml', //仅为示例，并非真实接口地址。
					method: 'GET',
					data: {
						ts: curTime,
						page: 1,
						pageSize: 10,
						activity_type: 'CLASS',
						tag_id: 'KRHNRTPJYX4000',
						hide_register: false
					},
					header: {
						Cookie: cookiestr
					}
				});
				const {
					data: {
						data: {
							rows: {
								0: { id: parent_class_id }
							}
						}
					}
				} = res[1];
				if (parent_class_id) {
					recordList.push(`获取 parent_class_id 成功 : ${parent_class_id}`);
					const res = await uni.request({
						url: 'https://tlearning-sdbg.tcl.com/api/bdm/activity/getBasicEntityList/activity_.shtml',
						method: 'GET',
						data: {
							ts: curTime,
							parent_class_id: parent_class_id
						},
						header: {
							Cookie: cookiestr
						}
					});
					const {
						data: { data: chapterDatas }
					} = res[1];
					if (Array.isArray(chapterDatas) && chapterDatas.length) {
						const chapterIds = chapterDatas.map(m => m.id);
						const registerModuleHistoryIds = [];
						const queryTestAnswerDetailsPromiseList = [];
						for (let activity_id of chapterIds) {
							const { status, data: fetchMHIdData } = await this.fetchMHId(parent_class_id, activity_id, cookiestr);
							if (!status) {
								recordList.push(` fetchMHId 失败 : ${activity_id} -- ${fetchMHIdData}`);
								continue;
							}
							const { 0: videoModel, 1: testModel } = fetchMHIdData;
							if (videoModel) {
								// 视频
								const { 0: videoRegId, 1: videoModId, 2: videoNModName, 3: videoModTimes, 4: videoLearnStatus } = videoModel;
								//学完就跳过
								if (!['已学完', '已合格'].includes(videoLearnStatus)) {
									const finishVidoLearnResult = await this.finishVidoLearn(videoRegId, videoModId, cookiestr, videoModTimes);
									recordList.push(`${videoNModName} -- ${finishVidoLearnResult}`);
								} else {
									recordList.push(`${videoNModName} -- ${videoLearnStatus}`);
								}
							}

							if (testModel) {
								// 测试
								const { 0: testRegId, 1: testModId, 2: testNModName, 4: testLearnStatus } = testModel;
								if (!['已学完', '已合格'].includes(testLearnStatus)) {
									// const initResult = await this.generateAnswerTest(testRegId, testModId, cookiestr);
									this.sleep(2000);
									const submitTestAnswerTrueResult = await this.submitTestAnswerTrue(testRegId, testModId, cookiestr);
									recordList.push(`${testNModName} -- ${submitTestAnswerTrueResult}`);
								} else {
									recordList.push(`${testNModName} -- ${testLearnStatus}`);
								}
							}
							this.sleep(1000);
						}

						this.submitLoading = false;
					}
				} else {
					recordList.push('获取 parent_class_id 失败');
				}
			} catch (e) {
				this.submitLoading = false;
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.main {
	padding: 20rpx;
}

.operater-x {
	margin: 10rpx 0;
}
</style>
